package com.md.config.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author 刘骄阳
 * 2022-04-22 15:22
 */
@Configuration
@Slf4j
public class FeignConfig implements RequestInterceptor {
  @Override
  public void apply(final RequestTemplate requestTemplate) {
    Optional.ofNullable(requestTemplate.body()).ifPresent(bytes -> log.info("入参: {}", new String(bytes)));
    // 设置日志Id
//    requestTemplate.header(ServerContextConstants.DATA_ID, (String) ServerContext.get(ServerContextConstants.DATA_ID));
//    requestTemplate.header(ServerContextConstants.ROOT_ID, (String) ServerContext.get(ServerContextConstants.ROOT_ID));
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (!ObjectUtils.isEmpty(attributes)) {
      HttpServletRequest request = attributes.getRequest();
      //添加token
      requestTemplate.header("token", request.getHeader("token"));
    }
  }
}
